package projorientado.ocr.vfeature.impl;

import java.util.Iterator;
import projorientado.image.ImageComparator;
import projorientado.image.ImageComparatorProvider;
import projorientado.ocr.OCRProvider;
import projorientado.ocr.vfeature.FeaturesComparator;
import projorientado.ocr.vfeature.FeaturesComparatorProvider;
import projorientado.ocr.vfeature.FeaturesPairExtractor;
import projorientado.ocr.vfeature.FeaturesPairExtractorProvider;
import projorientado.spi.ServiceProvider;
import projorientado.util.CodeTokenizer;
import projorientado.util.CodeTokenizer.CodeElement;
import projorientado.util.CodeTokenizer.CodeLine;
import projorientado.util.CodeTokenizer.CodeVarDef;

public class ImageFeaturesComparatorProvider implements ServiceProvider<ImageComparator> {

    private static final ImageFeaturesComparatorProvider instance = new ImageFeaturesComparatorProvider();
    
    static {
        ImageComparatorProvider.getInstance().registerServiceProvider("imageFeaturesComparator", instance);
    }
    
    private ImageFeaturesComparatorProvider() {
        
    }
    
    public static ImageFeaturesComparatorProvider getInstance() {
        return instance;
    }
    
    public ImageComparator getService(String s) {
        
        FeaturesPairExtractor extractor = null;
        FeaturesComparator comparator = null;
        
        CodeTokenizer.CodeBlock root = CodeTokenizer.singleParse(s);
        
        Iterator<CodeTokenizer.CodeElement> it = root.childs.iterator();
        while(it.hasNext()) {
            CodeElement e = it.next();
            if(e instanceof CodeTokenizer.CodeTextBlock) {
                CodeTokenizer.CodeTextBlock tblock = (CodeTokenizer.CodeTextBlock)e;
                String name = tblock.name.toLowerCase();
                
                if(name.startsWith("pairextractor:") || name.startsWith("featurespairextractor:")) {
                    String service = tblock.name.substring(name.indexOf(':')+1);
                    extractor = FeaturesPairExtractorProvider.getFeaturesPairExtractor(service,tblock.text);
                } else if(name.startsWith("comparator:") || name.startsWith("featurescomparator:")) {
                    String service = tblock.name.substring(name.indexOf(':')+1);
                    comparator = FeaturesComparatorProvider.getFeaturesComparator(service,tblock.text);
                }
            }
        }
        
        return new ImageFeaturesComparator(extractor,comparator);
    }

}
